/**
 * Created by apple on 16/12/8.
 */
var total = "";
var rows = 10;
var page_good = 1;
var data_good = new Array();
var good_info = "";//左下角的文章信息

var _name_before = "";
var _name_after = "";
var _cover_before = "";
var _cover_after = "";
var _count_before = "";
var _count_after = "";
var _price_before = "";
var _price_after = "";
var _description_before = "";
var _description_after = "";
var _input_id = ""; //图片上传时,每个input的data-id.其值为good-id;每一行(即同一个货物)的_input_id都相同
var _info = "";
var _good = "";

var _img_add = 0;

window.onload = function () {
    if (storage_admin_id) {
        select_change()

        $('#dataTables-example').dataTable();
        $("#sideNav").click(function () {
            if ($(this).hasClass('closed')) {
                $('.navbar-side').animate({left: '0px'});
                $(this).removeClass('closed');
                $('#page-wrapper').animate({'margin-left': '260px'});

            }
            else {
                $(this).addClass('closed');
                $('.navbar-side').animate({left: '-260px'});
                $('#page-wrapper').animate({'margin-left': '0px'});
            }
        });


    } else {
        window.location.href = "login.html"
    }
};

//商品列表信息
function good() {
    $.ajax({
        type: 'GET',
        url: "http://118.178.59.93:8080/Motocycle/api/v1/goods",
        data: data_good,
        async: false,
        success: function (data) {
            var obj = JSON.parse(data);
            try {
                if (obj.code == 0) {
                    total = obj.data.total;
                    var good_list_total = "";
                    $.each(obj.data.rows, function (i, item) {
                        good_list_total += "<tr>" +
                            "<td class='good_name'>" + item.good_name + "</td>" +
                            "<td class='good_cover'><img src='" + item.cover + "' data-id=" + item.good_id + " style='width: 100px'></td>" +
                            "<td class='good_count'>" + item.remain_count + "</td>" +
                            "<td class='good_price'>" + item.price + "</td>" +
                            "<td class='good_description' style='width: 350px;text-align: center'>" +
                            "<div class='good_description_img'>";
                        var _content_description = item.good_description.split(",");
                        for (var _a = 0; _a < _content_description.length; _a++) {
                            good_list_total += "<img src=" + _content_description[_a] + " style='width: 100px;margin: 10px' data-num=" + _a + " data-id=" + item.good_id + _a+">"
                        }
                        good_list_total += "</div></td>";
                        //主题
                        if (item.del_flag == 0) {
                            good_list_total += "<td style='width:9%;'>已上架</td>"
                        } else {
                            good_list_total += "<td></td>"
                        }

                        good_list_total += "<td style='margin: 5px 0;width: 15%;'>";
                        if (item.del_flag == 0) {
                            good_list_total += "<span class='operation_button good_delete' data-id=" + item.good_id + " style='background: #337AEB;' >下架</span>"
                        } else {
                            good_list_total += "<span class='operation_button good_add' data-id=" + item.good_id + " data-good-name=" + item.good_name + " data-remain-count=" + item.remain_count + " " +
                                "data-price=" + item.price + " data-good-description=" + item.good_description + " data-cover=" + item.cover + " style='background: #729c5c;' >上架</span>"
                        }
                        good_list_total += "<span class='operation_button good_revise' data-id=" + item.good_id + " style='background: #FF0100;' >修改</span>" +
                            "<span class='operation_button good_save'   data-id=" + item.good_id + " style='background: #FFBB0C;display: none;'>保存</span>" +
                            "</td></tr>"
                    });
                    $('#dataTables-example tbody').html(good_list_total);
                    page_good = data_good.page;
                }
            } catch (e) {

            }
        }
    })
}

//每页展示的数目不同
function select_change() {
    $('.pageNum').remove();
    $('#good_paginate').html('<div class="pageNum"></div>')
    rows = $("#select_change option:selected").val();
    page_good = 1;
    data_good = {
        page: page_good,
        rows: rows
    };
    good();
    if (rows > total) {
        good_info = "当前第 1 页 , 已展示 " + total + " 条 , 共 " + total + " 条数据";
    } else {
        good_info = "当前第 1 页 , 已展示 " + rows + " 条 , 共 " + total + " 条数据";
    }
    $('#good_info').html(good_info);
    //分页
    var _pagenum = Math.ceil(total / data_good.rows);
    if (_pagenum > 1) {
        var end_list = "";
        //需要分页展示
        $('.pageNum').show();
        $('.pageNum').createPage({
            pageCount: _pagenum,
            current: data_good.page,
            backFn: function (p) {
                //单击回调方法，p是当前页码
                data_good.page = p;
                end_list = p * data_good.rows;
                good();
                good_info = "当前第 " + p + " 页 , 已展示 " + end_list + " 条 , 共 " + total + " 条数据";
                $('#good_info').html(good_info)
            }
        });
    }
    $('.loading').hide()
}


//下架
$(document).on('click', '.good_delete', function () {
    var data_id = $(this).attr('data-id');
    layer.msg('您真的要下架该商品吗？', {
        time: 0, //不自动关闭
        btn: ['确定', '取消'],
        yes: function (index) {
            layer.close(index);
            $.ajax({
                type: 'DELETE',
                url: "http://118.178.59.93:8080/Motocycle/api/v1/goods?good_id=" + data_id,
                async: false,
                success: function (data) {
                    var obj = JSON.parse(data);
                    if (obj.code == 0) {
                        layer.msg('下架成功!', {time: 3000});
                        good();
                    }
                }
            })
        }
    });
});

//上架
$(document).on('click', '.good_add', function () {
    var data_id = $(this).attr('data-id');
    var data_good_name = $(this).attr('data-good-name');
    var data_remain_count = $(this).attr('data-remain-count');
    var data_price = $(this).attr('data-price');
    var data_cover = $(this).attr('data-cover');
    var data_good_description = $(this).attr('data-good-description');
    layer.msg('您真的要将该商品再次上架吗？', {
        time: 0, //不自动关闭
        btn: ['确定', '取消'],
        yes: function (index) {
            layer.close(index);
            $.ajax({
                type: 'post',
                url: "http://118.178.59.93:8080/Motocycle/api/v1/goods",
                data: {
                    good_id: data_id,
                    good_name: data_good_name,
                    remain_count: data_remain_count,
                    price: data_price,
                    cover: data_cover,
                    good_description: data_good_description
                },
                async: false,
                success: function (data) {
                    var obj = JSON.parse(data);
                    if (obj.code == 0) {
                        layer.msg('重新上架成功!', {time: 3000});
                        good();
                    }
                }
            })
        }
    });
});


//修改
$(document).on('click', '.good_revise', function () {
    //商品名字可修改
    _name_before = $(this).parents().parents('tr').find('.good_name').html();
    $(this).parents().parents('tr').find('.good_name').html("<input value=" + _name_before + ">");
    //简图可修改
    _cover_before = $(this).parents().parents('tr').find('.good_cover img').attr('src');
    _input_id = $(this).parents().parents('tr').find('.good_cover img').attr('data-id');
    $(this).parents().parents('tr').find('.good_cover').append("<input type='file' id='file" + _input_id + "' data-id=" + _input_id + " style='margin:0 auto;width: 165px;' onchange='setImagePreview(this,"+_input_id+");'>");
    //库存数量
    _count_before = $(this).parents().parents('tr').find('.good_count').html();
    $(this).parents().parents('tr').find('.good_count').html("<input value=" + _count_before + " style='width: 50px;'>");
    //单价
    _price_before = $(this).parents().parents('tr').find('.good_price').html();
    $(this).parents().parents('tr').find('.good_price').html("<input value=" + _price_before + " style='width: 50px;'>");
    //修改图片
    var _length = $(this).parents().parents('tr').find('.good_description_img img').length;
    $(this).parents().parents('tr').find('.good_description_img img').each(function (i, item) {
        var _input_num=_input_id+i;
        $(this).after("<input type='file' id='file" + _input_num + "' data-id=" + _input_num + " style='margin:0 auto;width: 165px;' onchange='setImagePreview(this,"+_input_num+");'>");
        _description_before+=$(this).attr('src')+","
    });
    if (_length < 5) {
        _img_add = 5 - _length;
        var info = "<label>可添加新图片(最多)" + _img_add + "张</label>" +
            "<div id='container'><input type='file' name='file' id='pickfiles' style='margin:0 auto;width: 165px;' multiple>" +
            "</div>" +
            "<div id='filelist' style='height: 0;overflow-y: auto;'></div>";
        $(this).parents().parents('tr').find('.good_description').append(info);
        pic_more();
    }
    _description_before=_description_before.substring(0,_description_before.length-1);
    //按钮变化
    $(this).parents().parents('tr').find('.good_add').hide();
    $(this).parents().parents('tr').find('.good_delete').hide();
    $(this).parents().parents('tr').find('.good_revise').hide();
    $(this).parents().parents('tr').find('.good_save').show();
});

//保存
$(document).on('click', '.good_save', function () {
    _good = $(this).attr('data-id');
    _info = $(this).parents().parents('tr');
    _name_after = _info.find('.good_name input').val();
    _cover_after = _info.find('.good_cover img').attr('src');
    _count_after = _info.find('.good_count input').val();
    _price_after = _info.find('.good_price input').val();
    _info.find('.good_description_img img').each(function (i, item) {
        _description_after+=$(this).attr('src')+","
    });

    _description_after=_description_after.substring(0,_description_after.length-1);


    if (_name_after == _name_before) {
        if (_cover_after == _cover_before) {
            if (_count_after == _count_before) {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //什么都没有修改
                        $('.loading').hide();
                        save_old_good();
                    } else {
                        //只修改了描述
                        data_good = {good_id: _good, good_description: _description_after};
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //只修改了单价
                        data_good = {good_id: _good, price: _price_after};
                        save_new_good();
                    } else {
                        //修改了单价+描述
                        data_good = {good_id: _good, price: _price_after, good_description: _description_after};
                        save_new_good();
                    }
                }
            } else {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //只修改了库存
                        data_good = {good_id: _good, remain_count: _count_after};
                        save_new_good();
                    } else {
                        //修改了库存+描述
                        data_good = {good_id: _good, remain_count: _count_after, good_description: _description_after};
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了库存+单价
                        data_good = {good_id: _good, remain_count: _count_after, price: _price_after};
                        save_new_good();
                    } else {
                        //修改了库存+单价+描述
                        data_good = {
                            good_id: _good,
                            remain_count: _count_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            }
        } else {
            if (_count_after == _count_before) {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //只修改了简图
                        data_good = {good_id: _good, cover: _cover_after};
                        save_new_good();
                    } else {
                        //修改了简图+描述
                        data_good = {good_id: _good, cover: _cover_after, good_description: _description_after};
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了简图+单价
                        data_good = {good_id: _good, cover: _cover_after, price: _price_after};
                        save_new_good();
                    } else {
                        //修改了简图+单价+描述
                        data_good = {
                            good_id: _good,
                            cover: _cover_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            } else {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //修改了简图+库存
                        data_good = {good_id: _good, cover: _cover_after, remain_count: _count_after};
                        save_new_good();
                    } else {
                        //修改了简图+库存+描述
                        data_good = {
                            good_id: _good,
                            cover: _cover_after,
                            remain_count: _count_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了简图+库存+单价
                        data_good = {
                            good_id: _good,
                            cover: _cover_after,
                            remain_count: _count_after,
                            price: _price_after
                        };
                        save_new_good();
                    } else {
                        //修改了简图+库存+单价+描述
                        data_good = {
                            good_id: _good,
                            cover: _cover_after,
                            remain_count: _count_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            }
        }

    } else {
        if (_cover_after == _cover_before) {
            if (_count_after == _count_before) {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //修改了名称
                        data_good = {good_id: _good, good_name: _name_after};
                        save_new_good();
                    } else {
                        //修改了名称+描述
                        data_good = {good_id: _good, good_name: _name_after, good_description: _description_after};
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了名称+单价
                        data_good = {good_id: _good, good_name: _name_after, price: _price_after};
                        save_new_good();
                    } else {
                        //修改了名称+单价+描述
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            } else {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //只修改了库存
                        data_good = {good_id: _good, remain_count: _count_after};
                        save_new_good();
                    } else {
                        //修改了库存+描述
                        data_good = {good_id: _good, remain_count: _count_after, good_description: _description_after};
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了名称+库存+单价
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            remain_count: _count_after,
                            price: _price_after
                        };
                        save_new_good();
                    } else {
                        //修改了名称+库存+单价+描述
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            remain_count: _count_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            }
        } else {
            if (_count_after == _count_before) {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //修改了名称+简图
                        data_good = {good_id: _good, good_name: _name_after, cover: _cover_after};
                        save_new_good();
                    } else {
                        //修改了名称+简图+描述
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            cover: _cover_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了名称+简图+单价
                        data_good = {good_id: _good, good_name: _name_after, cover: _cover_after, price: _price_after};
                        save_new_good();
                    } else {
                        //修改了名称+简图+单价+描述
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            cover: _cover_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            } else {
                if (_price_after == _price_before) {
                    if (_description_after == _description_before) {
                        //修改了名称+简图+库存
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            cover: _cover_after,
                            remain_count: _count_after
                        };
                        save_new_good();
                    } else {
                        //修改了名称+简图+库存+描述
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            cover: _cover_after,
                            remain_count: _count_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                } else {
                    if (_description_after == _description_before) {
                        //修改了名称+简图+库存+单价
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            cover: _cover_after,
                            remain_count: _count_after,
                            price: _price_after
                        };
                        save_new_good();
                    } else {
                        //修改了名称+简图+库存+单价+描述
                        data_good = {
                            good_id: _good,
                            good_name: _name_after,
                            cover: _cover_after,
                            remain_count: _count_after,
                            price: _price_after,
                            good_description: _description_after
                        };
                        save_new_good();
                    }
                }
            }
        }
    }
});


//未修改任何东西情况下的保存
function save_old_good() {
    layer.msg('您没有进行过任何修改,是否退出本次编辑？', {
        time: 0, //不自动关闭
        btn: ['确定', '取消'],
        yes: function (index) {
            layer.close(index);
            //名字
            _info.find('.good_name').html(_name_after);
            //简图
            _info.find('.good_cover input').remove();
            //库存
            _info.find('.good_count').html(_count_after);
            //单价
            _info.find('.good_price').html(_price_after);
            //描述
            _info.find('.good_description input').remove();
            _info.find('.good_description label').remove();
            //按钮变化
            _info.find('.good_delete').show();
            _info.find('.good_add').show();
            _info.find('.good_revise').show();
            _info.find('.good_save').hide();
        }
    });
}

//有修改内容情况下的保存
function save_new_good() {
    $.ajax({
        type: "PUT",
        url: "http://118.178.59.93:8080/Motocycle/api/v1/goods",
        data: data_good,
        async: false,
        success: function (data) {
            try {
                var obj = JSON.parse(data);
                if (obj.code == 0) {
                    //名字
                    _info.find('.good_name').html(_name_after);
                    //简图
                    _info.find('.good_cover img').attr('src', _cover_after);
                    _info.find('.good_cover input').remove();
                    //库存
                    _info.find('.good_count').html(_count_after);
                    //单价
                    _info.find('.good_price').html(_price_after);

                    var _content_description = _description_after.split(",");
                    var _good_description_img="";
                    for (var _a = 0; _a < _content_description.length; _a++) {
                        _good_description_img += "<img src=" + _content_description[_a] + " style='width: 100px;margin: 10px'>"
                    }

                    //描述
                    _info.find('.good_description_img').html(_good_description_img);
                    _info.find('.good_description input').remove();
                    _info.find('.good_description label').remove();

                    //按钮变化
                    _info.find('.good_delete').show();
                    _info.find('.good_add').show();
                    _info.find('.good_revise').show();
                    _info.find('.good_save').hide();

                    layer.msg("操作成功!", {time: 3000})
                }
            } catch (e) {
                layer.msg(data.msg, {time: 3000})
            }
        }
    })
}


//上传图片
function setImagePreview(file,id) {
    $('.loading').show();
    _input_id=id;
    if (file.files && file.files[0]) {
        var postfix = file.files[0].name.split('.').pop();
        if (postfix != "jpg" && postfix != "gif" && postfix != "png" && postfix != "jpeg") {
            $('.loading').hide();
            layer.msg("上传仅支持：jpg,gif,png,jpeg格式")
        } else {
            var reader = new FileReader();
            var ext = '.' + file.files[0].name.split('.').pop();
            reader.onload = function (evt) {
                //加载图片获取图片真实宽度和高度
                var image = new Image();
                image.onload = function () {
                    //图片上传又拍云
                    var config = {
                        bucket: 'motorcycle',
                        expiration: parseInt((new Date().getTime() + 3600000) / 1000),
                        // 尽量不要使用直接传表单 API 的方式，以防泄露造成安全隐患
                        form_api_secret: '0jWegIsJu9xVxJMrgp4ydONAxok='
                    };
                    var instance = new Sand(config);
                    instance.upload("Image/" + parseInt((new Date().getTime() + 3600000) / 1000) + ext);

                };
                image.src = evt.target.result;
            };
            reader.readAsDataURL(file.files[0]);
        }
    } else {
        $('.loading').hide();
    }

}


document.addEventListener('uploaded', function (e) {
    for (var key in e.detail) {
        if (key === 'path') {
            var img_url = "http://motorcycle.b0.upaiyun.com" + e.detail[key];
                $('.good_cover img').each(function (i, item) {
                    var _id = $(this).attr('data-id');
                    if (_input_id == _id) {
                        $(this).attr('src', img_url);
                        $('.loading').hide();
                    }
                });
            $('.good_description_img img').each(function (i, item) {
                var _id = $(this).attr('data-id');
                if (_input_id == _id) {
                    $(this).attr('src', img_url);
                    $('.loading').hide();
                }
            });
        }

    }
});


//多图上传
function pic_more() {
    var options = {
        'bucket': 'motorcycle',
        'save-key': '/Image/{filemd5}{.suffix}',
        'expiration': Math.floor(new Date().getTime() / 1000) + 86400
    };
    // 上传请求的相关参数
    var policy = window.btoa(JSON.stringify(options));
    // 从 UPYUN 用户管理后台获取表单 API
    var form_api_secret = '0jWegIsJu9xVxJMrgp4ydONAxok=';
    // 计算签名
    var signature = md5(policy + '&' + form_api_secret);

    //多图上传
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: 'pickfiles', // you can pass in id...
        container: document.getElementById('container'), // ... or DOM Element itself
        url: 'http://v0.api.upyun.com/' + options.bucket,
        filters: [
            {title: "Image files", extensions: "jpg,gif,png,jpeg"}
        ],
        multipart_params: {
            'Filename': '${filename}', // adding this to keep consistency across the runtimes
            'Content-Type': '',
            'policy': policy,
            'signature': signature
        },

        init: {
            PostInit: function () {
                $(document).on('click', '.exchanges_submit', function () {
                    uploader.start();
                });
            },

            FilesAdded: function (up, files) {
                if (files.length > _img_add) {
                    layer.msg("最多只能上传" + _img_add + "张图片!");
                    uploader.start();

                } else {
                    plupload.each(files, function (file) {
                        $('.exchanges_span').append('<span id=' + file.id + '></span>');
                    });
                    for (var i = 0; i < files.length; i++) {
                        if (files && files[i]) {
                            $('.exchanges').show();
                            var reader = new FileReader();
                            reader.readAsDataURL(files[i].getNative());
                            reader.onload = function (e) {
                                var image = new Image();
                                image.src = e.target.result;
                                image.onload = function () {
                                    $('.exchanges_image').append('<img src="' + image.src + ' " ><span></span>');
                                };
                            }

                        }
                    }
                }

            },

            UploadProgress: function (up, file) {
                if ($('.exchanges').css("display") == "block") {
                    document.getElementById(file.id).innerHTML = file.percent + "%";
                }
            },

            //单个文件上传完成
            FileUploaded: function (up, file, info) {
                if ($('.exchanges').css("display") == "block") {
                    var response = JSON.parse(info.response);
                    var _url = 'http://motorcycle.b0.upaiyun.com' + response.url;
                    $('.good_description_img').each(function () {
                        var _id = $(this).attr('data-id');
                        if (_input_id == _id) {
                            $(this).append('<img src="' + _url + ' " style="width: 100px;margin: 10px" >');
                        }
                    });
                }


            },
            //所有文件上传完成
            UploadComplete: function (up, files) {
                if ($('.exchanges').css("display") == "block") {
                    $('.exchanges_image').html('');
                    $('.exchanges_span').html('');
                    $('.exchanges').hide();
                    $('.good_description_img').each(function () {
                        var _id = $(this).attr('data-id');
                        if (_input_id == _id) {
                            _img_add = 5 - $(this).find('img').length;
                            if (_img_add > 0) {
                                $('.good_description label').html("可添加新图片(最多)" + _img_add + "张")
                            } else {
                                $('.good_description label').remove();
                                $('#container').remove();
                            }
                        }
                    });
                }


            },
            Error: function (up, err) {
                layer.msg("服务器跑火星啦~~~待会儿再来吧~~~")
            }
        }
    });

    uploader.init();
}


